package cn.acyou.actions.createEntity;

import cn.acyou.utils.CommonUtil;
import cn.acyou.utils.DateUtil;
import cn.acyou.utils.MessageUtil;
import cn.acyou.utils.SampleDialogWrapper;
import com.alibaba.fastjson.JSON;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;

/**
 * 通过JSON创建实体操作
 * @author youfang
 * @version [1.0.0, 2021/3/26]
 **/
public class CreateEntityFromJsonAction extends AnAction {
    /**
     * Implement this method to provide your action handler.
     *
     * @param e Carries information on the invocation place
     */
    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        SampleDialogWrapper dialog = new SampleDialogWrapper("通过JSON创建实体");
        VirtualFile actionFolder = e.getData(LangDataKeys.VIRTUAL_FILE);
        String packageName = ProjectRootManager.getInstance(project).getFileIndex().getPackageNameByDirectory(actionFolder);

        if (dialog.showAndGet()) {
            String className = dialog.getFileName();
            String jsonText = dialog.getFileContent();
            writeEntityClass(packageName, className, actionFolder.getPath(), jsonText, project);
            // Refresh UI
            try {
                Thread.sleep(100);
                ProjectView.getInstance(project).refresh();
                actionFolder.refresh(false, true);
            } catch (InterruptedException ignored) {
            }
        }
    }

    private void writeEntityClass(String packageName, String className, String fileRealPath, String jsonText, Project project) {
        LinkedHashMap<String, Object> jsonTextMap = null;
        try {
            jsonTextMap = JSON.parseObject(jsonText, LinkedHashMap.class);
        } catch (Exception e) {
            String message = "创建失败，请检查JSON格式！";
            Notification success = MessageUtil.notifyGroup.createNotification(message, NotificationType.INFORMATION);
            Notifications.Bus.notify(success, project);
            return;
        }

        List<String> voContentList = new ArrayList<>();
        voContentList.add("package " + packageName + ";\r\n");
        voContentList.add("\r\n");
        voContentList.add("import java.io.Serializable;\r\n");
        voContentList.add("import lombok.Data;\r\n");
        voContentList.add("\r\n");
        voContentList.add("\r\n");
        voContentList.add("/**\r\n");
        voContentList.add(" * " + className + "\r\n");
        voContentList.add(" * @version [1.0.0, " + DateUtil.getNowSpecificString() + "] \r\n");
        voContentList.add(" */ \r\n");
        voContentList.add("@Data\r\n");
        voContentList.add("public class " + className + " implements Serializable {\r\n");
        voContentList.add("\r\n");
        voContentList.add("    private static final long serialVersionUID = " + new Random().nextLong() + "L;\r\n");
        for (String fieldKey : jsonTextMap.keySet()) {
            voContentList.add("\r\n");
            voContentList.add("    private String " + fieldKey + ";\r\n");
        }
        voContentList.add("\r\n");
        voContentList.add("}");

        new File(fileRealPath).mkdirs();
        File directory = new File(fileRealPath + "\\" + className + ".java");
        try {
            CommonUtil.writeFiles(directory, voContentList);
        } catch (Exception e) {
            String message = "创建失败，请检查格式！";
            Notification success = MessageUtil.notifyGroup.createNotification(message, NotificationType.INFORMATION);
            Notifications.Bus.notify(success, project);
        }
    }

    @Override
    public void update(AnActionEvent event) {
        Project project = event.getProject();
        VirtualFile actionFolder = event.getData(LangDataKeys.VIRTUAL_FILE);

        if (project != null && actionFolder != null && actionFolder.isDirectory()) {
            String packageName = ProjectRootManager.getInstance(project).getFileIndex().getPackageNameByDirectory(actionFolder);
            event.getPresentation().setVisible(packageName != null);
        } else {
            event.getPresentation().setVisible(false);
        }
    }


}
